package easyexcel.controller;

import easyexcel.exception.BusinessException;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: jichao
 * @date: 2021/5/18 15:05
 */
@RestController
@RequestMapping("/api/info")
public class uploadController {

    @Value("${img.location}")
    private String path;

    @PostMapping("/upload")
    public String upload(@RequestParam("files") MultipartFile file) {

        String targetPath = path + "/" + file.getOriginalFilename(); //这个是文件的路径

     /*   if(file.isEmpty()){
            throw new BusinessException("请选择文件！");
        }*/

        File filePath = new File(path); //这个是存放文件的目录


        while (!filePath.exists()) {
            filePath.mkdirs();
        }

        //啦啦啦啦！新增test分支

        try {
            file.transferTo(new File(targetPath)); //注意此时的filePath是目标文件夹+文件名字，切记！！不要只搞成目标文件夹了
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "上传成功";
    }

    @GetMapping("/getIp")
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

}
